<template>
  <div>
    <el-table
      ref="multipleTable"
      :data="menuRoleList"
      style="width: 100%"
      row-key="id"
      lazy
    >
      <el-table-column prop="name" label="菜单名" />
      <el-table-column prop="path" label="菜单路径" />
      <el-table-column prop="component" label="组件" />
      <el-table-column label="权限是否开启">
        <template slot-scope="scope">
          <el-switch
            :active-value="scope.row.roleId === null"
            :inactive-value="scope.row.roleId !== null"
            @change="change(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="total"
      @prev-click="currentChange"
      @next-click="currentChange"
      @current-change="currentChange"
    />
  </div>
</template>

<script>
import { Message } from 'element-ui'

export default {
  name: 'MenuDialog',
  props: {
    roleId: Number
  },
  data() {
    return {
      query: '',

      menuRoleList: [],

      total: 0,
      page: 0,
      pageSize: 5
    }
  },
  mounted() {
    this.doSelectAll()
  },
  methods: {
    currentChange(index) {
      this.page = index - 1
      this.doSelectAll()
    },

    doSelectAll() {
      this.$store
        .dispatch('roleMenu/selectAll', {
          roleId: this.roleId,
          name: this.query,
          page: this.page,
          pageSize: this.pageSize
        })
        .then((res) => {
          this.menuRoleList = res.list
          this.total = res.total
        })
    },

    change(menuRole) {
      if (menuRole.roleId === null) {
        this.add(menuRole)
        menuRole.roleId = this.roleId
      } else {
        this.del(menuRole.menuRoleId)
        menuRole.roleId = null
      }
    },

    add(menuRole) {
      this.$store
        .dispatch('roleMenu/add', {
          roleId: this.roleId,
          menuId: menuRole.menuId
        })
        .then((res) => {
          Message({
            type: 'success',
            message: '开启成功',
            duration: 5 * 1000
          })
          menuRole.menuRoleId = res.data
        })
    },

    del(menuRoleId) {
      this.$store
        .dispatch('roleMenu/del', {
          menuRoleId: menuRoleId
        })
        .then((res) => {
          Message({
            type: 'success',
            message: '关闭成功',
            duration: 5 * 1000
          })
        })
    }
  }
}
</script>

<style scoped>
</style>
